<?php
namespace app\index\controller;

use think\Controller;
use think\Db;
use Workerman\Worker;
use Workerman\Timer;
use pmhapp\Pmhapp;

class Script extends Controller
{
    public function k(){
        return 1;
    }
    
    /**
     * 群发脚本请求接口
     * 作者@ qq32579136
     * web@ https://www.pmhapp.com
     * 
     * $id 任务主键ID
     * $key 密钥
    **/
    public function script_timing($name,$id,$key){
        $tom = Db::name('TimingOfMass')->where(['id'=>$id])->find();
        
        //验证KEY
        if($tom['key'] != $key){
            //关闭程序
            $config = fopen("script/".$name, "w") or die("Unable to open file!");
            $txt = 2;
            fwrite($config,$txt);
            Db::name('TimingOfMass')->where(['id'=>$id])->update(['type'=>1]);
        }
        //dump($tom['timing']);
        
        $timing = 60/$tom['timing'];//多少分钟执行一次
        //bug修复 2022/1/1 10:27
       // $timing = intp(60,$tom['timing']);
        
        
        $timing = $timing*60;//秒
        
        
        
        
        if(isset($tom['tom_time']) && $tom['tom_time'] != ''){
            $time = time();
            
            $time = $time-$tom['tom_time'];
            
            if($time < $timing){
                exit();
            }
        }
        
        //执行
        $server_name = $_SERVER["SERVER_NAME"];
        
        //查询实例
        $example = Db::name('example')->where(['id'=>$tom['exampleId']])->find();
        if(!$example){
            exit();
        }
        
        $data = json_decode($tom['data'],true);
        $url = [];
        //提取群url
        foreach ($data as $key => &$value){
            $TgQun = Db::name('TgQun')->where(['id'=>$value['qunId']])->find();
            array_push($url,$TgQun['url']);
        }       
        
        //提取图片
        $tom['image'] = json_decode($tom['image'],true);
        
        //执行时间
        $time = time();
        $update = Db::name('TimingOfMass')->where(['id'=>$id])->update(['tom_time'=>$time]);
        
        $a = new \pmhapp\Pmhapp();
        
        if($tom['content'] && empty($tom['image'])){
            //true true 
            $a->异步发消息($example['name'],$tom['content'],$url);
        }else if(!$tom['content'] && !empty($tom['image'])){
            //true true
            foreach ($tom['image'] as $key){
               $imgurl = 'https://'.$server_name.'/'.$key;
               $a->异步发媒体($example['name'],$imgurl,$tom['content'],$url);  
            }
        }else{
            foreach ($tom['image'] as $key){
               $imgurl = 'https://'.$server_name.'/'.$key;
               $a->异步发媒体($example['name'],$imgurl,$tom['content'],$url);  
            }
        }
        
    }
}